/**
 * 等比缩放
 * @param {HTMLElement} 元素
 * @param {number} 容器宽度
 */
function setScale(element, containerWidth) {
  const size = document.documentElement.clientWidth / containerWidth
  const size2 = `${100 / size}%`
  element.setAttribute('style', `transform:scale(${size});transform-origin:0 0;width:${size2};height:${size2};`)
}
/**
 * 高级防抖
 * @param {Function} func 要执行的函数
 * @param {number} delay 延时
 * @param {Boolean} immediate 是否立即执行一次
 * @returns
 */
function debounce(func, delay, immediate) {
  let timer
  return function () {
    timer && clearTimeout(timer)
    if (immediate) {
      const firstRun = !timer
      timer = setTimeout(() => {
        timer = null
      }, delay)
      if (firstRun)
        func.apply(this, arguments)
    }
    else {
      timer = setTimeout(() => {
        func.apply(this, arguments)
      }, delay)
    }
  }
}

/**
 * 禁止手动缩放
 */
function disableManualScale() {
  // 禁止Ctrl+滑轮缩放
  window.addEventListener('mousewheel', (event) => {
    if (event.ctrlKey === true || event.metaKey)
      event.preventDefault()
  }, { passive: false })

  // firefox浏览器
  window.addEventListener('DOMMouseScroll', (event) => {
    if (event.ctrlKey === true || event.metaKey)
      event.preventDefault()
  }, { passive: false })

  // 禁止Ctrl+ +/- 缩放
  document.addEventListener('keydown', (event) => {
    if ((event.ctrlKey === true || event.metaKey === true) && (event.key === '+' || event.key === '=' || event.key === '-' || event.key === '_'))
      event.preventDefault()
  }, false)
}

/**
 * 启用等比缩放
 * @param {HTMLElement} 元素
 * @param {number} 容器宽度
 * @param {number} 延迟
 */
function enableScale(element, containerWidth = 1920, delay = 0) {
  setScale(element, containerWidth)
  window.addEventListener('resize', debounce(() => {
    setScale(element, containerWidth)
  }, delay), { passive: true })
  disableManualScale()
}

export { enableScale }
